//
//  CLLOAuthViewController.swift
//  CLWeiNo
//
//  Created by DDC on 2017/10/12.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit
import SVProgressHUD
/// 授权登录界面
class CLLOAuthViewController: UIViewController {

    fileprivate lazy var webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        
        view.backgroundColor = UIColor.white
        // 导航栏返回按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontsize: 16, action: #selector(back), target: self)
        // 导航栏自动填充按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontsize: 16, action: #selector(autoFill), target: self)
        // delegate
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(CLLWBAppKey)&redirect_uri=\(CLLWBRedirectURI)"
        guard let url = URL(string: urlString) else {
            return
        }
        let request = URLRequest(url: url)
        webView.loadRequest(request)
        // 设置webView的属性
        webView.scrollView.isScrollEnabled = false
        
    }

    /// 返回
    @objc func back(){
        dismiss(animated: true, completion: nil)
    }
    /// 自动填充
    @objc func autoFill(){
        let js = "document.getElementById('userId').value = 'jimmychenliang@sina.com';" + "document.getElementById('passwd').value = 'j15607103133';"
        webView.stringByEvaluatingJavaScript(from: js)
    }
    

   
}

// MARK: - UIWebViewDelegate
extension CLLOAuthViewController :UIWebViewDelegate {
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    
        if request.url?.absoluteString .hasPrefix(CLLWBRedirectURI) == false {
            return true
        }
        
        if request.url?.query?.hasPrefix("code=") == false {
            
            back()
            return true
        }
        
        
        // 获得code
        let code = request.url?.query?.substring(from: "code=".endIndex)
        
        // 加载授权信息
        CLLNetWorkManager.shared.loadAccessToken(code: code!) { (isSuccess) in
            
            if !isSuccess {
                SVProgressHUD.showError(withStatus: "登录失败")
            }else {
                
                SVProgressHUD.showInfo(withStatus: "登录成功")
                // 注册通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: CLLWBUserLogonSuccessNotification), object: nil)
                // 关闭授权页面
                self.back()
            }
        }
        
        return false
    }
    func webViewDidStartLoad(_ webView: UIWebView) {
        // 显示提示
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        // 移除显示
        SVProgressHUD.dismiss()
    }
    
}
